/**
 * 查岗功能模块：
 * 
 * 功能描述：
 *  绑定到主页面查岗数据栏，并定时查询查岗信息，根据情况弹窗显示
 */


PostQueryGrid = {};

PostQueryGrid.debug = true;//调试许可

PostQueryGrid.divId = "";
PostQueryGrid.userId = 0;//定义用户id
PostQueryGrid.userType = "";//定义用户类型
PostQueryGrid.userName = "";//定义用户名称
PostQueryGrid.comNoList = [];//定义经营许可证号列表
PostQueryGrid.comNoMap = {};//定义保存所有comNo和对应用户名称的相关信息

PostQueryGrid.dataList = [];//定义临时存储查岗数据


PostQueryGrid.slctTime = "30s" ;//定义查岗数据查询时间
PostQueryGrid.slctTimerName = "slctPostQueryTimer850302";
PostQueryGrid.pupWintime = '500ms';//定义弹窗间隔时间
PostQueryGrid.pupWinTimerName = 'pupQuesWinTimer850302';

PostQueryGrid.slctTimeLength = 1000 * 60 * 60 * 1;//定义查询最近一个小时的数据
PostQueryGrid.slctUrl = globalConfig.webPath + "/basicSlctAction/basicSelectData.action";
PostQueryGrid.slctPaginationUrl = globalConfig.webPath + "/basicSlctAction/basicSelectPaginationData.action";










////////////////////////////////////////////////////////////////////////初始化

//初始化
PostQueryGrid.init = function (divId, userInfo) {
    this.divId = divId;
    if (!DataUtil.isDefined(userInfo.id)) {
        this.userId = userInfo.id;
    }
    //  DataUtil.outDebug("divId : " + divId);
    //  DataUtil.outDebug("userInfo:" , userInfo);
    if (this.divId != "") {
        this.initDataGrid();
        if(this.userId > 0){
            this.getUserList();//获取企业许可证号数据
        }else{
            DataUtil.outError("postQuery-->获取用户信息失败，无法获取企业许可证号!");
        }
    } else {
        DataUtil.outError("postQuery-->查岗区域控件id为空，无法完成初始化！");
    }
}

//初始化datagrid
PostQueryGrid.initDataGrid = function () {
    let that = this;
    this.postDataGrid = $("#" + this.divId);
    this.postDataGrid.datagrid({
        columns: [[
            { title: '时间', field: 'createDate', width: 120, minWidth: 80 },
            { title: '监管平台', field: 'cmdData',formatter:that.formatPostComNo, width: 80, minWidth: 80 },
            { title: '类型', field: 'type',formatter:that.formatPostType, width: 70, minWidth: 70 },
            // { title: '命令id', field: 'cmdId', width: 65 , minWidth: 50},
            // { title: '流水号', field: 'resId', width: 70, minWidth: 70 },
            { title: '结果', field: 'status', formatter:that.formatPostStatus, width: 50, minWidth: 50 },
            { title: '描述', field: 'body', width: 160, minWidth: 160 },
            { title: '应答内容', field: 'answ', width: 60, minWidth: 60 },
            { title: '应答人', field: 'owner', width: 60, minWidth: 60 },
            { title: '平台经营许可证号', field: 'comNo', width: 90, minWidth: 90 },

            //下面三个字段暂不需要
            //{ title: '颜色', field: 'plateColor', width: 45,minWidth:60 },
            // { title: 'Sim卡号', field: 'simNo', width: 105,minWidth:120 },
            // { title: 'id', field: 'id', width: 0,minWidth:0 }
        ]],
        fit: true,
        // toolbar:"#alarmGridToolbar",
        striped: true,
        fitColumns: true,
        singleSelect: true,
        rownumbers: true,
        pagination: true,
        nowrap: true,
        pageSize: 10,
        onDblClickRow: that.onDblClickRow,//表格的双击事件定义
        pageList: [10, 20, 50, 100, 150, 200],
        showFooter: true,
    });

    this.postDataGrid.datagrid("getPager").pagination({
        onSelectPage: function (pageNumber, pageSize) {
            that.slctAllData();
        }
    });
}

///////////////////////////////////////////////////////数据格式化
//格式化查岗类型
PostQueryGrid.formatPostType = function(value,rowData,rowIndex){
    let str = "";
    if(value == "1"){
        str = "下级平台";
    }else if(value == "2"){
        str = "平台单一业户";
    }else if(value == '3'){
        str = "平台所有业户";
    }
    return str;
}

//格式化状态
PostQueryGrid.formatPostStatus = function(value,rowData,rowIndex){
    let str = "";
    // DataUtil.outDebug('value = ' + value + " , type = " + typeof(value));
    if(!DataUtil.isDefined(value) && value == "发送成功"){
        str = "已回复";
    }
    return str;
}

//格式化企业许可证号
PostQueryGrid.formatPostComNo = function(value,rowData,rowIndex){
    // DataUtil.outDebug("rowData:" , rowData);
    let map = PostQueryGrid.comNoMap;
    let str = '';
    if(rowData.type == '2' && !DataUtil.isDefined(map)){
        if(!DataUtil.isDefined(map[rowData.comNo])){
            str = map[rowData.comNo];
        }
    }
    return str;
}



//表格双击事件
PostQueryGrid.onDblClickRow = function (rowIndex, rowData) {
    // PostQueryGrid.outDebug("第 " + rowIndex + " 行表格双击事件：" ,rowData)
    if(!DataUtil.isDefined(rowData)){
        let cmdId = rowData.cmdId;
        let url = globalConfig.webPath+"/platformPostQuery/view.action?commandId=" + cmdId;
        if(!DataUtil.isDefined(rowData.answ)){
            if(rowData.answ != ""){
                url += '&answ=' + rowData.answ;
            }
        }
        // InfoWindow.open(url, 630,350,);
        DataUtil.openInfoWindow(url, 630, 350, "上级平台查岗");
    }
}



////////////////////////////////////////////////////////////////////////数据操作

//获取企业许可证号列表
PostQueryGrid.getUserList = function(){
    let that = this;
    let url = globalConfig.webPath + "/basicSlctAction/basicSelectData.action";
    let param = {};
    param.userId = this.userId;
    param.queryId = "user.selectUsers";
    Utility.getAjaxData(url,JSON.stringify(param),function(data){
        // that.outDebug("接收到用户信息：" , data);
        if(data.success){
            let flg = false;
            if(!DataUtil.isDefined(data.data) &&  data.data.length > 0){
                for(let i=0 ; i< data.data.length ; i++){
                    let item = data.data[i];
                    if(item.userId == that.userId){
                        // that.outDebug("查找到用户信息" + item.userId + " ，序号为：" + i + " , data: " , item);
                        if(that.getUserData(item) == ""){
                            flg = true;
                            break;
                        }
                    }
                }
            }
            // DataUtil.outDebug("comNoMap = " , that.comNoMap);
            if(flg ==  true){
                //通过用户信息，查询企业经营许可证号
                that.getComNoDatas();
            }else{
                DataUtil.outError("postQuery-->获取用户基本信息失败!");
            }
        }else{
            DataUtil.outError("postQuery-->" + data.message);
        }
    });
}

//获取用户信息数据
PostQueryGrid.getUserData = function(data){
    let msg = "";
    // 
    if(!DataUtil.isDefined(data.userType)){
        if(data.userType != ""){
            this.userType = data.userType;
        }else{
            msg += "用户类型信息为空！";
        }
    }else{
        msg += "用户类型信息不存在！";
    }

    if(!DataUtil.isDefined(data.name)){
        if(data.name != ""){
            this.userName = data.name;
        }else{
            msg += "用户名称数据为空！";
        }
    }else{
        msg += "用户名称数据不存在！";
    }
    // this.outDebug('获取信息结果：' + msg);
    return msg;
}


//获取企业经营许可证号数据
PostQueryGrid.getComNoDatas = function(){
    let that = this;
    let url = globalConfig.webPath + "/basicSlctAction/basicSelectData.action";
    let param = {};
    param.userId = this.userId;
    param.queryId = "dataProcess.selectAllComNoDtas";
    Utility.getAjaxData(url,JSON.stringify(param),function(data){
        // DataUtil.outDebug("获取到企业经营许可证号数据 : " , data);
        if(data.success){
            if(!DataUtil.isDefined(data.data) && data.data.length > 0){
                that.comNoList = [];
                that.comNoMap = {};
                $.each(data.data,function(n,item){
                    //解析
                    that.formatOneDepComNo(item);
                });
            }
            if(that.comNoList.length >= 0){
                //成功
                // DataUtil.outDebug("获取企业经营许可证号成功！");
                // DataUtil.outDebug("comNoList:" , that.comNoList);
                // DataUtil.outDebug("comNoMap : " , that.comNoMap);
                if(that.comNoList.length > 0){
                    that.startService();
                }else{
                    DataUtil.outDebug("postQuery-->当前用户名下企业没有经营许可证号");
                }
            }else{
                DataUtil.outError("postQuery-->获取企业经营许可证号失败！");
            }
        }else{
            DataUtil.outError("postQuery-->获取企业经营许可证号失败：" + data.message);
        }
    });
}

//解析单个许可证号数据
PostQueryGrid.formatOneDepComNo = function(data){
    let that = this;
    if(!DataUtil.isDefined(data.roadPermitNo) && data.roadPermitNo != ""){
        let list = data.roadPermitNo.split(",");
        if(list.length > 0){
            for(let i=0 ; i<list.length ; i++){
                // DataUtil.outDebug("typeof key = " + typeof(list[i]));
                if(DataUtil.isDefined(that.comNoMap[list[i]])){
                    that.comNoMap[list[i]] = DataUtil.isDefined(data.depName) ? "未知" : data.depName;
                }else{
                    that.comNoMap[list[i]] += DataUtil.isDefined(data.depName) ? " , 未知" :  " ," + data.depName;
                }
                //判断并插入列表
                if(that.comNoList.indexOf(list[i]) < 0){
                    that.comNoList.push(list[i]);
                }
            }
        }
    }
}

//开始服务
PostQueryGrid.startService = function(){
    let that =  this;
    $(document).everyTime(that.slctTime,that.slctTimerName,function(){
        try {
            that.slctAllData();
        } catch (error) {
            DataUtil.outError("postQuery-->" + "获取查岗数据错误：" + error);
        }
    });
}

// 查询数据
PostQueryGrid.slctAllData = function(){
    let that = this;
    // let temp = new Date().getTime() - this.slctTimeLength;
    let now = new Date();
    let param = {};
    param.queryId = "dataProcess.selectNowPostQueryDatas";//查询语句
    param.cmd = '37632';
    param.subCmd = '37633';
    param.resCmd = '4864';
    param.resSubCmd = '4865';
    param.status = '发送成功';
    // param.createDate = Utility.dateToString(new Date(temp));
    param.createDate = now.getFullYear() + "-" + (now.getMonth() + 1) + "-" + now.getDate() + " 00:00:00";
    // param.owner = that.userName;//需要名称获取所有的回复 
    if(that.userType != "admin"){
        param.outType = 1;//定义不需要查询的类型，即如果为企业用户，则不需要全查,需要排除掉平台查岗
        param.comNoList = that.comNoList;
    }

    //分页数据
    param.pageNumber = that.postDataGrid.datagrid("getPager").data("pagination").options.pageNumber;
	param.pageSize = that.postDataGrid.datagrid("getPager").data("pagination").options.pageSize;

    // this.outDebug("开始查询查岗数据,参数为：" , param);
    Utility.getAjaxData(that.slctPaginationUrl,JSON.stringify(param),function(data){
        if(data.success){
            // that.outDebug("查岗数据：" , data.data);
            that.postDataGrid.datagrid("loadData",data.data);
            that.managePostDatas(data.data);
        }else{
            DataUtil.outError("postQuery-->查询查岗数据失败：" + data.message);
        }
    });
}


//处理所有查岗
PostQueryGrid.managePostDatas = function(data){
    let that = this;
    if(!DataUtil.isDefined(data.rows)){
        if(data.rows.length > 0){
            that.dataList = [];
            let index = 0;
            $.each(data.rows,function(n,item){
                if(DataUtil.isDefined(item.answ)){//未回答,弹窗显示
                    // that.outDebug("弹出窗口，序号：" + (n+1))
                    item.index = index;
                    let cmdId = item.cmdId;
                    item.title = "上级平台查岗" + item.resId;
                    item.url = globalConfig.webPath + "/platformPostQuery/view.action?commandId=" + cmdId;
                    item.time = 0;
                    if(!DataUtil.isDefined(item.createDate)){
                        item.time = new Date(item.createDate).getTime();
                    }
                    that.dataList.push(item);
                    index ++;
                }
            });
            //开始处理数据

            if (that.dataList.length > 0) {
                //处理第一个查岗数据
                // that.manageOnePostData(that.dataList[0]);//
                //弹窗
                let index = 0;
                $(document).everyTime(that.pupWintime,that.pupWinTimerName,function(){
                    if(index < that.dataList.length){
                        that.outDebug("开始处理第" + index + "个问题窗口");
                        that.manageOnePostData(that.dataList[index]);
                        index ++;
                    }else{
                        $(document).stopTime(that.pupWinTimerName);
                    }
                });
            }
        }
    }
}


/**
 * 处理单个查岗数据
 * @param data,数据
 * @param url，弹窗地址
 * @param name，弹窗标题
 */
PostQueryGrid.manageOnePostData = function(item){
    let that = this;
    that.outDebug("开始处理单个未回复问题，索引为：" + item.index + "  , 相关数据为：" , item);
    if(!DataUtil.isDefined(item.time)){
        if(item.time > 0){//时间不为0，判断条件并进行处理
            let now = new Date().getTime();
            if(now - item.time >= 1000 * 60 * 10){//超过10分钟，开始自动回复
                that.outDebug("当前问题出现超过10分钟， 开始进行自动回复！");
                that.autoPostOneAnswData(item);
            }else{
                //不超过10分钟，则不进行回复，只弹出
                that.outDebug("当前问题出现未超过10分钟， 不进行自动回复，仅弹出!");
                item.answer = "";
                //用户类型不为admin，弹出
                if(that.userType != 'admin'){
                    that.pupPostWindow(item);//无答案弹出
                }else{
                    //管理员，如果问题类型为1，弹出，其他不管
                    if(item.type == 1){
                        that.pupPostWindow(item);//无答案弹出
                    }
                }
            }
        }else{//时间为0，立即开始进行自动回复处理
            that.outDebug("当前问题时间数值为0，不进行时间判断， 开始进行自动回复！");
            that.autoPostOneAnswData(item);
        }
    }else{//时间数据不合法，自动回复
        that.outDebug("当前问题时间属性不存在，无法进行时间判断， 开始进行自动回复！");
        that.autoPostOneAnswData(item);
    }
}

//自动回复
PostQueryGrid.autoPostOneAnswData = function(item){
    let that = this;
    
    let param = {};
    param.queryId = "postQueryLib.selectPostQueryDatas";
    param.quesBody = item.body;
    Utility.getAjaxData(that.slctUrl,JSON.stringify(param),function(data){
        let answ = "";
        if(data.success){
            if(!DataUtil.isDefined(data.data) && data.data.length > 0){
                //题库中有数据，获取计算结果
                answ = that.getQuesLibResult(data.data[0]);
            }else{
                //其他，没有获取到正常结果 , 获取计算题验证数据
                answ = that.getCalQuesResult(item);
            }
            
        }else{
            DataUtil.outError("查询查岗数据失败，题目为：" + data.body + " ， 失败原因：" + data.message);
        }
        
        //计算结果为空，根据时间判断是否超过10分钟
        if(answ == "" && item.time > 0){
            let now = new Date().getTime();
            if(now - item.time > 1000 * 60 * 10){
                DataUtil.outDebug("超过10分钟无回复，自动回复收到，当前数据为数据为：",item);
                answ = "收到";
            }
        }

        item.answer = answ;//保存answer
        //2.如果有结果，自动回复，
        if(answ != ""){
            // that.outDebug("当前题目为：" + item.body + "自动计算结果为：" + answ);
            that.autoSendAnsw(item,function(data){
                if(data.success){
                    //自动回复成功
                    that.pupPostWindow(item);//带答案弹出
                }else{
                    //自动回复失败！
                    DataUtil.outError("题目：" + item.body + "自动回复失败：" + data.message);
                    //无答案弹出
                    item.answer = "";
                    that.pupPostWindow(item);
                }
            });
        }else{
            // that.outDebug("当前题目为：" + item.body + "自动计算结果为空：" + answ + "!");
            that.pupPostWindow(item);//无答案弹出
        }
    });
}


//获取题库计算结果,返回计算结果
PostQueryGrid.getQuesLibResult = function(data){
    let answ = "";
    if(!DataUtil.isDefined(data)){
        if(data.type == "val"){
            answ = DataUtil.isDefined(data.result) ? "" : data.result + "";
        }else{
            // this.outDebug("开始计算题库返回结果，题目：" + data.quesBody  + " , 代码为：" + data.code);
            try {
                if(!DataUtil.isDefined(data.code)){
                    //不带参方法
                    this.libFun = new Function(data.code);
                    // DataUtil.outDebug("libFun = " , this.libFun);
                    if(typeof(this.libFun) == "function"){
                        answ = this.libFun();
                        // DataUtil.outDebug("题库问题：" + data.quesBody + " , 题库方法执行结果：" + answ);
                    }
                }
            } catch (error) {
                DataUtil.outError("执行题库代码失败，题库问题：" + data.quesBody + " ， 失败原因：" + error);
            }
        }
    }
    return answ;
}

//获取计算题计算结果，返回计算结果----------------------------------未完成
PostQueryGrid.getCalQuesResult = function(item){
    let answ = "";

    return answ;
}


//自动回复，接收到回复结果后调用回调结果
PostQueryGrid.autoSendAnsw = function(item,callback){
    let that = this;
    let msg = "";

    //校验数据
    let list = ['resId','comNo','body','type','answer'];
    $.each(list,function(n,key){
        if(DataUtil.isDefined(item[key])){
            msg += "问题" + item[body] + "中的" + key + "值不存在，无法自动回复！";
        }
    });
    //发送自动回复数据
    if (msg == "") {
        let url = globalConfig.webPath + "/platformPostQuery/send.action"
            + '?platformId=0&infoId=' + item.resId + '&objId=' + item.comNo
            + '&content=' + item.body + '&objType=' + item.type + '&answer=' + (item.answer+'');
        // that.outDebug("sendUrl = " + url);
        let param = {message:"send"};
        try {
            Utility.getAjaxData(url, JSON.stringify(param), function (data) {
                that.outDebug("接收到自动回复响应：" , data);
                //回调方法
                if (typeof (callback) == "function") {
                    callback(data);
                }
            });
        } catch (error) {
            DataUtil.outError("发送自动回复失败：" + error);
        }
    } else {
        DataUtil.outError(msg);
    }
    
}


//弹出窗口
PostQueryGrid.pupPostWindow = function(item){
    try {
        // DataUtil.outDebug("当前数据：" , item);
        if(!DataUtil.isDefined(item.url) && !DataUtil.isDefined(item.title) && !DataUtil.isDefined(item.answer)){
            // this.outDebug("开始弹窗！");
            if(item.answer != ""){
                item.url  += '&answ=' + item.answer;
            }
            DataUtil.openInfoWindow(item.url, 630, 350, item.title);
            
            AlarmSound.playPost();//播放声音
        }else{
            DataUtil.outError(item.body + "弹窗地址或者标题缺失，无法弹出查岗窗口！");
        }
    } catch (error) {
        DataUtil.outError(item.body + "弹出查岗窗口失败：" + error);
    }
    // let index = item.index + 1;
    // if(index < this.dataList.length){
    //     this.manageOnePostData(this.dataList[index]);
    // }
}





////////////////////////////////////////////////////////////////////////基础方法

//输出信息
PostQueryGrid.outDebug = function(msg,data){
    if(this.debug){
        DataUtil.outDebug(msg,data);
    }
}

//根据星期，获取星期描述
PostQueryGrid.getWeekStr = function(week){
    let weekStr = "";
    switch (week) {
        case 1:
            weekStr = "星期一";
            break;
        case 2:
            weekStr = "星期二";
            break;
        case 3:
            weekStr = "星期三";
            break;
        case 4:
            weekStr = "星期四";
            break;
        case 5:
            weekStr = "星期五";
            break;
        case 6:
            weekStr = "星期六";
            break;
        case 7:
            weekStr = "星期日";
            break;
    }
    return weekStr;
}